package com.UI;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

public class TTTActivity extends Activity
{
	String imageUrl = "http://dynamic.12306.cn/TrainQuery/passCodeAction.do?rand=rrand?";
	Bitmap bmImg;
	ImageView imView;
	Button button1;
	EditText et;
  
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		imView = (ImageView) findViewById(R.id.imview);
		et = (EditText) findViewById(R.id.et);

		findViewById(R.id.btn).setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				//testgetCookies();
			}
		});
		findViewById(R.id.btn1).setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View v)
			{	
				
				GetDataAsyncTask getDataAsyncTask = new GetDataAsyncTask(TTTActivity.this);
				getDataAsyncTask.execute("");
			}
		});
	}

	  

	private void getCookies()
	{
//		try
//		{
//			DefaultHttpClient httpclient = new DefaultHttpClient();
//			HttpPost request = new HttpPost(imageUrl);
//			HttpResponse response = httpclient.execute(request);
//			cookies = httpclient.getCookieStore().getCookies();
//			HttpEntity entity = response.getEntity();
//			if (entity != null)
//			{
//				entity.consumeContent();
//			}
//			if (cookies.isEmpty())
//			{
//				Log.i(TAG, "-------Cookie NONE---------");
//			} else
//			{
//				for (int i = 0; i < cookies.size(); i++)
//				{
//					Log.i(TAG, "- domain " + cookies.get(i).getDomain());
//					Log.i(TAG, "- path " + cookies.get(i).getPath());
//					Log.i(TAG, "- value " + cookies.get(i).getValue());
//					Log.i(TAG, "- name " + cookies.get(i).getName());
//					Log.i(TAG, "- port " + cookies.get(i).getPorts());
//					Log.i(TAG, "- comment " + cookies.get(i).getComment());
//					Log.i(TAG, "- commenturl" + cookies.get(i).getCommentURL());
//					Log.i(TAG, "- all " + cookies.get(i).toString());
//				}
//			}
//			httpclient.getConnectionManager().shutdown();
//		} catch (Exception e)
//		{
//			 
//		}

	}


}
class GetDataAsyncTask extends AsyncTask<String, Integer, String>
{
	private Context mContext;
	private Handler handler;
	ProgressDialog progressDialog;
	String TAG = "TAG";
	String url = "http://dynamic.12306.cn/TrainQuery/passTrainInfoByStation.jsp";
	List<Cookie> cookies;
	String result = "";
	/**
	 * 
	 */
	public GetDataAsyncTask(Context context)
	{
		this.mContext = context;
	}

	public GetDataAsyncTask(Context context, Handler handler)
	{
		this.mContext = context;
		this.handler = handler;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.os.AsyncTask#doInBackground(Params[])
	 */
	
	@Override
	protected String doInBackground(String... params)
	{
		
		for(int i = 0; i < 50;i++)
		{	
			String rusult = test("5");
			if (!rusult.contains("锟斤拷锟斤拷"))
			{
				 Log.i("tag", rusult);
				break;
			} 
			else {
				testgetCookies();
			}
		}
		return result;
	}

	@Override
	protected void onPreExecute()
	{

		progressDialog = ProgressDialog.show(mContext, "","锟斤拷取锟斤拷锟斤拷校锟斤拷锟斤拷缘锟�锟斤拷",true,true);
		
	}

	@Override
	protected void onProgressUpdate(Integer... values)
	{
		 
	}

	@Override
	protected void onPostExecute(String result)
	{
		progressDialog.dismiss();
 		System.out.println(result);
//		Bundle data = new Bundle();
//		data.putString("msg", result);
//		 
//		Message message = new Message();
//		message.setData(data);
//		handler.sendMessage(message);
	}
	
	
	private void testgetCookies()
	{
		DefaultHttpClient mHttpClient = new DefaultHttpClient();
		HttpPost mPost = new HttpPost("http://dynamic.12306.cn/TrainQuery/passCodeAction.do?rand=rrand?");
		List<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
		try
		{
			mPost.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8));
		} catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		}
		HttpResponse response;
		InputStream is ;
		try
		{
			response = mHttpClient.execute(mPost);
			HttpEntity entity = response.getEntity();
//			is = entity.getContent();
//			Bitmap bitmap = BitmapFactory.decodeStream(is);
//			imView.setImageBitmap(bitmap);
			cookies = mHttpClient.getCookieStore().getCookies();
			 
		}catch (Exception e)
		{
			e.printStackTrace();
		}
		 
	}

	private String test(String rand)
	{
		String result ="锟斤拷锟斤拷";
		try
		{
			 
			DefaultHttpClient mHttpClient = new DefaultHttpClient();
			HttpPost mPost = new HttpPost("http://dynamic.12306.cn/TrainQuery/iframeTrainPassStationByTrainCode.jsp");
			String CiVlkRggf2 = cookies.get(0).getName();
			String CiVlkRggf2Vaule = cookies.get(0).getValue();
			String JSESSIONID = cookies.get(1).getName();
			String JSESSIONIDValue = cookies.get(1).getValue();

			mPost.addHeader("Cookie", JSESSIONID + "=" + JSESSIONIDValue);
			mPost.addHeader("Cookie", CiVlkRggf2 + "=" + CiVlkRggf2Vaule);
			mPost.addHeader("BIGipServerotsweb", "2513691111.36895.0000");

			List<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
			pairs.add(new BasicNameValuePair("nmonth1", "03"));
			pairs.add(new BasicNameValuePair("nmonth1_new_value", "false"));
			pairs.add(new BasicNameValuePair("nday1", "24"));
			pairs.add(new BasicNameValuePair("nday1_new_value", "false"));
			pairs.add(new BasicNameValuePair("trainCode1", "1172"));
			pairs.add(new BasicNameValuePair("trainCode1_new_value", "false"));
			pairs.add(new BasicNameValuePair("randCode", rand));

			String strPairs = pairs.toString();
			System.out.println(strPairs);
			mPost.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8));

			HttpResponse response = mHttpClient.execute(mPost);
			
			if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK)
			{
				result = EntityUtils.toString(response.getEntity());
				//System.out.println(result);
			}
			
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		return result;
	}
	
 

}
